package Demo1;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-08-25
 * Time: 14:24
 */
public class Test {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //二叉树的右视图
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if(root == null) return list;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            while(size != 0){
                //读取元素
                TreeNode tmp = queue.poll();

                //最右边节点
                if(size == 1){
                    list.add(tmp.val);
                }

                //拓展队列元素
                if(tmp.left != null){
                    queue.offer(tmp.left);
                }

                if(tmp.right != null){
                    queue.offer(tmp.right);
                }
                size--;
            }
        }
        return list;
    }

    //二叉树展开成链表
    //记录前一个节点
    public TreeNode prev = null;
    public void flatten(TreeNode root) {
        if(root == null) return;

        //记录当前节点的右孩子节点，防止被修改后找不到右孩子节点
        TreeNode tmp = root.right;

        //修改指向
        if(prev != null) prev.right = root;
        prev = root;

        flatten(root.left);

        //遍历完左树的节点
        root.left = null;


        flatten(tmp);
    }
    public static void main(String[] args) {

    }
}
